package org.paradise.dms.dao.impl;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.paradise.dms.pojo.AllocationInfo;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

import com.dheaven.framework.dao.BaseHibernateDao;
import com.dheaven.framework.dao.DaoException;

@Service
@SuppressWarnings("unchecked")
public class SystemMgrDAOImpl extends BaseHibernateDao {
	private static Logger log = Logger.getLogger(SystemMgrDAOImpl.class);

	/**
	 * 
	 * Description:分页查询预分配type
	 * 
	 * @Version1.0 Apr 11, 2009 8:02:14 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param pageSize
	 * @param startRow
	 * @return
	 */
	public List<AllocationInfo> listAllPreassignTypeByPage(int pageSize, int startRow) {
		final int pageSize1 = pageSize;
		final int startRow1 = startRow;
		return this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public List doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery("FROM AllocationInfo");
				query.setFirstResult(startRow1);
				query.setMaxResults(pageSize1);
				return query.list();
			}
		});
	}

	/**
	 * 
	 * Description:返回总行数
	 * 
	 * @Version1.0 Apr 11, 2009 8:11:25 PM 李双江（paradise.lsj@gmail.com）创建
	 * @return
	 */
	public int getAllPreassignTypeRows() {
		return this.find("from AllocationInfo").size();
	}

	/**
	 * 
	 * Description:根据preid删除一条预分配标记值
	 * 
	 * @Version1.0 Apr 11, 2009 8:32:06 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param allocationid
	 * @return
	 */
	public String deleltePreassignTypeByID(final String allocationid) throws DaoException {
		String statusMsg = "";

		boolean allocationIdNotInUse = (Boolean) this.getHibernateTemplate().execute(new HibernateCallback() {
			public Boolean doInHibernate(Session session) {
				SQLQuery query = (SQLQuery) session.createSQLQuery("select count(studentid) from student where studentpreasignedid=? group by studentpreasignedid");
				query.setInteger(0, Integer.parseInt(allocationid));
				log.info(query.list().size() + "--------");
				if (query.list() != null && query.list().size() > 0) {
					if (Integer.parseInt(query.list().get(0) + "") > 0)
						return false;
				}
				query = (SQLQuery) session.createSQLQuery("select count(dormitoryid) from dormitory where allocationid=? group by allocationid");
				query.setInteger(0, Integer.parseInt(allocationid));

				if (query.list() != null && query.list().size() > 0) {
					if (Integer.parseInt(query.list().get(0) + "") > 0)
						return false;
				}
				return true;
			}
		});

		if (!allocationIdNotInUse) {
			statusMsg = "预分配标记使用中，无法删除！";
			log.warn("DMS_warn:预分配标记使用中，无法删除！");
			return statusMsg;
		}

		try {
			AllocationInfo ai = (AllocationInfo) this.find("from AllocationInfo where allocationid=?", new Object[] { allocationid }).get(0);
			this.delete(ai);
			statusMsg = "删除id为" + allocationid + "的预标记值成功！";
			log.info("DMS_info:" + statusMsg);
			return statusMsg;
		} catch (DaoException e) {
			log.error("DMS_error:删除id为 " + allocationid + "失败");
			log.error("失败原因 " + e);
		}
		return null;
	}

	/**
	 * 
	 * Description:插入一条预分配标记值
	 * 
	 * @Version1.0 Apr 11, 2009 8:52:50 PM 李双江（paradise.lsj@gmail.com）创建
	 * @param preassigntypename
	 * @return
	 */
	public String insertPreassignType(String preassigntypename,String starttime,String endtime) {

		try {
			List<AllocationInfo> list = this.find("from AllocationInfo where allocationname=?", new Object[] { preassigntypename });
			if (list != null && list.size() > 0) {
				log.warn("DMS_warn:预分配值" + preassigntypename + "已经存在!");
				return "预分配值" + preassigntypename + "已经存在";
			} else {
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date sdate = null;
				Date edate = null;
				try {
					sdate = df.parse(starttime);
					edate = df.parse(endtime);
				} catch (ParseException e1) {
					e1.printStackTrace();
				}
				AllocationInfo ai = new AllocationInfo();
				ai.setAllocationname(preassigntypename);
				ai.setStarttime(sdate);
				ai.setEndtime(edate);
				this.create(ai);
				log.info("DMS_info:向数据库插入名称为：" + preassigntypename + "的预分配值成功！");
				return "插入成功！";
			}
		} catch (DaoException e) {
			log.error("DMS_error:向数据库插入名称为： " + preassigntypename + "的预分配值失败");
			log.error("失败原因 " + e);
		}
		return "添加失败！";
	}

}
